<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\API\CreateDeviceInspectOrderRequest;
use App\Models\Device;
use App\Models\DeviceInspector;
use App\Models\DeviceInspectOrder;
use App\Http\Controllers\AppBaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use InfyOm\Generator\InfyOmGeneratorServiceProvider;

class DeviceInspectOrderController extends AppBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($deviceId, Request $request)
    {
        $paginate = $request->get('limit') ?? 20;
        return $this->sendResponse(DeviceInspectOrder::where(['device_id' => $deviceId])->paginate(15), 'success');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\API\CreateDeviceInspectOrderRequest $request
     * @return string
     */
    public function store(CreateDeviceInspectOrderRequest $request)
    {
        $data = array_merge($request->all(), [
            'record_date' => time(),
            'operator' =>Auth::user()->toArray()['true_name']
        ]);

        $result = DeviceInspectOrder::Create($data);
        if($result){
            Device::where("id",$result->device_id)->update(['status'=>303]);
        }
        return $result ?
            $this->sendResponse($result, '创建成功') :
            $this->sendApiError('创建失败', 'failed');
    }

    public function getDeviceDetail($deviceId)
    {
        if (empty($deviceId)) {
            return $this->sendApiError('设备ID不能为空');
        }

        $deviceDetail = Device::where(['id' => $deviceId])->first()->toArray();

        // 查询该设备最近的一条记录
        $lastOrder = DeviceInspectOrder::where(['device_id' => $deviceId])->latest('id')->first();
        $lastOrder = empty($lastOrder) ? [] : $lastOrder->toArray();

        // 获取设备类型的维保设置
        $deviceInspectorSetting = DeviceInspector::where([
                'device_type' => $deviceDetail['type'],
                'device_brand' => $deviceDetail['brand'],
                'device_model' => $deviceDetail['spec']
            ])
            ->first();
        $deviceInspectorSetting = empty($deviceInspectorSetting) ? [] : $deviceInspectorSetting->toArray();


        // 计算 剩余天数 是否逾期 下次维护时间 累计使用天数
        if(isset($deviceInspectorSetting['inspect_period'])) {
            $remind_days = $deviceInspectorSetting['inspect_period'] - (
                empty($lastOrder) ?
                    (int)((time() - strtotime($deviceDetail['use_time'])) / (3600 * 24)) :
                    (int)((time() - strtotime($lastOrder['inspect_date'])) / (3600 * 24))
                );
        } else {
            $remind_days = 0;
        }
        if (empty($deviceInspectorSetting)) {
            $inspectData = [];
        } else {
            $inspectData = [
                // 剩余天数
                'remind_days' => $remind_days,
                // 是否逾期
                'is_out_day' => $this->_getRemindDays($remind_days),
                'next_inspect' => empty($lastOrder) ?
                    date('Y-m-d', strtotime(
                        "+ {$deviceInspectorSetting['inspect_period']} days",
                        strtotime($deviceDetail['use_time'])
                    )) :
                    date('Y-m-d', strtotime(
                        "+ {$deviceInspectorSetting['inspect_period']} days",
                        strtotime($lastOrder['inspect_date'])
                    )),
                'use_days' => (int)((time() - strtotime($deviceDetail['use_time'])) / (3600 * 24)),
            ];
        }

        $data =[
            'baseInformation' => $deviceDetail,
            'inspectData' => $inspectData
        ];

        return $this->sendResponse($data, '请求成功');
    }

    private function _getRemindDays($remind_days)
    {

        switch ($remind_days) {
            case $remind_days < 0 : {
                $result = '已逾期';
                break;
            }
            case $remind_days >= 0 && $remind_days < 7 : {
                $result = '待维护';
                break;
            }

            case $remind_days > 7 : {
                $result = '已维护';
                break;
            }
            default:
                $result = '未维护';
        }
        return $result;
    }
}
